package com.csust.educodesandbox.codesandbox.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;

import com.csust.educodesandbox.codesandbox.CodeSandBox;
import com.csust.educodesandbox.enums.JudgeStatusEnum;
import com.csust.educodesandbox.model.ExecuteCodeRequest;
import com.csust.educodesandbox.model.ExecuteCodeResponse;
import com.csust.educodesandbox.model.ExecuteMessage;
import com.csust.educodesandbox.model.JudgeInfo;
import com.csust.educodesandbox.utils.ProcessUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @ClassNameJavaNativeCodeSandBox
 * @Description java原生代码沙箱
 * @Author钰玟
 * @Date2025/6/25 下午3:52
 * @Version 1.0
 **/
@Slf4j
@Component
public class JavaNativeCodeSandBox implements CodeSandBox {
    //全局代码存储位置
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    /**
     * 黑名单
     */
    private static final List<String> blackList = Arrays.asList("Files", "exec");
    /**
     * 全局java类名
     */
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    /**
     * 时间限制
     */
    private static final long TIME_OUT = 5000L;
    /**
     * 字典树
     */
    private static final WordTree WORD_TREE = new WordTree();
    static{
        // 添加黑名单
        WORD_TREE.addWords(blackList);
    }
    public static void main(String[] args) {
        CodeSandBox codeSandBox = new JavaNativeCodeSandBox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
//        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);//主程序args输入
//        String code = ResourceUtil.readStr("testCode/unsafeCode/MemoryError.java", StandardCharsets.UTF_8);//危险程序测试
        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);//输入流测试
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = codeSandBox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        /**
         * Java 进程类 Process
         */
        //获取执行用例
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //1.把用户的代码保存为文件
        //1.1获取用户的工作目录
        String userDir = System.getProperty("user.dir");
        //1.2 为每个用户划分一个保存文件的目录
        //使用 File.pathSeparator 来保证不同系统的兼容性
        String workPath = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if (!FileUtil.exist(workPath)) {
            //不存在，则创建该目录
            FileUtil.mkdir(workPath);
        }
        //把用户的代码隔离存放
        String userCodeParentPath = workPath + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        //2.编译代码，得到 class 文件
        //2.1 拼接编译命令
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        //2.2使用 Runtime.getRuntime().exec() 执行命令
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            //2.3使用 ProcessUtil工具类获取执行信息

            ExecuteMessage executeMessage = ProcessUtil.processExecuteAndGetMessage(compileProcess, "编译");
            log.info("编译信息：{}", executeMessage);
        } catch (IOException e) {
            log.error("编译错误:{}", e.getMessage());
            return getExecuteCodeResponseByException(e);
        }
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        //3.执行代码，得到输出结果
        //3.1从inputList中获取输入参数
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                // For safe because 超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        log.error("程序运行超时");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);

                    }
                }).start();
//                ExecuteMessage executeMessage = ProcessUtil.processExecuteAndGetMessage(runProcess, "运行"); //命令行
                ExecuteMessage executeMessage = ProcessUtil.runInteractProcessAndGetMessage(runProcess, "运行");//输入流

                //将结果放入列表中
                executeMessageList.add(executeMessage);
                log.info("运行结果：{}", executeMessage);
            } catch (Exception e) {
                log.error("运行异常", e);
                return getExecuteCodeResponseByException(e);
            }
        }
        //4.收集整理输出结果
        //4.1 构造响应结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        //4.2 获取输出列表
        List<String> outputList = new ArrayList<>();
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            //反向判断。判断错误的输出
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                //设置状态为3  枚举
                executeCodeResponse.setStatus(JudgeStatusEnum.FAILED.getValue());
                break;
            }
            if(ObjUtil.isNotNull(executeMessage.getTime())){
                maxTime = Math.max(maxTime, executeMessage.getTime());
            }
            outputList.add(executeMessage.getMessage());
        }

        if (outputList.size() == executeMessageList.size()) {
            //运行成功 设置为 1
            executeCodeResponse.setStatus(JudgeStatusEnum.RUNNING.getValue());
        }
        //设置输出列表
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        //设置时间
        judgeInfo.setTime(maxTime);

        executeCodeResponse.setJudgeInfo(judgeInfo);

        //5.文件清理，释放空间
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            log.info("删除{}", del ? "成功" : "失败");
        }

        return executeCodeResponse;
    }
    //错误处理，提升程序健壮性
    private ExecuteCodeResponse getExecuteCodeResponseByException(Throwable e) {
        return ExecuteCodeResponse.builder()
                .outputList(new ArrayList<>())
                .message(e.getMessage())
                .status(2) // 表示代码沙箱错误
                .judgeInfo(new JudgeInfo()).build();
    }
}
